package vn.edu.saigontech.ncms.web.interceptor;

import org.hibernate.Session;
import org.hibernate.Transaction;

import vn.edu.saigontech.ncms.util.HibernateUtil;
import vn.edu.saigontech.ncms.web.BaseAction;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public class TransactionInterceptor extends AbstractInterceptor {
	
	public String intercept(ActionInvocation invocation) throws Exception {
		BaseAction action = (BaseAction)invocation.getAction();
		String result = Action.ERROR;
		Session session = null;
		Transaction trans = null;
		try {
			session = HibernateUtil.getCurrentSession();
			trans = session.beginTransaction();
			result = invocation.invoke();
			trans.commit();
		}
		catch(Exception ex) {
			if(trans != null) {
				trans.rollback();
			}
			ex.printStackTrace();
			action.setValueMessage("hasError", ": " + ex.getClass().getName() + ".. " + ex.getMessage());
		}
		finally {
			if(session != null) {
				session.close();
			}
		}
		return result;
	}
}
